﻿namespace Sage.FreeSqlManager.Tenant
{
    /// <summary>
    /// 租户作用域 - 用于临时切换租户上下文
    /// </summary>
    /// <remarks>
    /// 使用using语句创建作用域，确保租户上下文在退出作用域时恢复
    /// </remarks>
    public sealed class TenantScope : IDisposable
    {
        private readonly long _originalTenantId;

        /// <summary>
        /// 获取作用域内使用的FreeSql实例
        /// </summary>
        public IFreeSql FreeSql { get; }

        /// <summary>
        /// 获取作用域内设置的租户ID
        /// </summary>
        public long TenantId { get; }

        /// <summary>
        /// 初始化租户作用域
        /// </summary>
        /// <param name="freeSql">FreeSql实例</param>
        /// <param name="tenantId">要切换到的租户ID</param>
        /// <exception cref="ArgumentNullException">freeSql为null时抛出</exception>
        public TenantScope(IFreeSql freeSql, long tenantId)
        {
            FreeSql = freeSql ?? throw new ArgumentNullException(nameof(freeSql));
            TenantId = tenantId;

            // 保存原始租户ID以便恢复
            _originalTenantId = TenantManager.Current;

            // 设置新的租户ID
            TenantManager.Current = tenantId;
        }

        /// <summary>
        /// 释放资源，恢复原始租户ID
        /// </summary>
        public void Dispose()
        {
            // 恢复原始租户ID
            TenantManager.Current = _originalTenantId;
        }
    }
}
